package org.jeecg.modules.front.interceptor;



import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.front.entity.resp.BusUserResp;
import org.jeecg.modules.front.consts.WebConst;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;

@Slf4j
public class UserContext implements Serializable {

    private static final long serialVersionUID = -6634783591580517814L;

    private static ThreadLocal<String> userIdThreadLocal = new ThreadLocal<>();

    private static ThreadLocal<String> sessionIdThreadLocal = new ThreadLocal<>();

//    private static ThreadLocal<SysUserDTO> userThreadLocal = new ThreadLocal<>();

    private static ThreadLocal<BusUserResp> sysThreadLocal = new ThreadLocal<>();




    public static String getUserId() {
        String userId = userIdThreadLocal.get();
        if (StringUtils.isEmpty(userId)) {
            // 去session里面取
            userId = getUser() != null ? getUser().getUserId() : null;
        }
        return userId;
    }

    /**
     * 获取租户ID
     *
     * @return
     */
    public static String getTenantId() {

//        SysUserDTO user = getUser();
//        if (user == null) {
        return "";
//        }
//
//        return user.getTenantId();
    }

    public static void setUserId(String userId) {
        userIdThreadLocal.set(userId);
    }

    public static String getSessionId() {
        return sessionIdThreadLocal.get();
    }

    public static void setSessionId(String sessionIdId) {
        sessionIdThreadLocal.set(sessionIdId);
    }

    public static void removeUserSession() {
        userIdThreadLocal.remove();
        sessionIdThreadLocal.remove();
//        userThreadLocal.remove();
        sysThreadLocal.remove();
    }

    /**
     * 判断用户是否登录
     *
     * @return
     * @author zhong.wenlong 2018-12-25
     */
    public static final Boolean isUserLogin() {
        // 看是否获取可以获取登录用户
        BusUserResp userDTO = getUser();
        if (userDTO != null) {
            return true;
        }
        return false;
    }

    /**
     * 获取当前servlet的session对象，不在servlet环境下返回null.
     *
     * @return
     * @author Ji.kai 2018-11-5
     */
    public static final HttpSession getSession() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) {
            log.warn("获取当前servlet的ServletRequestAttributes对象失败，ServletRequestAttributes为空！");
            return null;
        }
        HttpServletRequest req = attrs.getRequest();
        if (req == null) {
            log.warn("获取当前servlet的request对象失败，HttpServletRequest为空！");
            return null;
        }
        HttpSession session = req.getSession(true);
        if (session == null) {
            log.warn("获取当前Session对象失败，HttpSession为空！");
        }
        return session;
    }

    /**
     * 获取当前登录的用户信息,没有登录则返回null
     *
     * @return
     * @author Ji.kai 2018-11-5
     */
    public static final BusUserResp getUser() {

        BusUserResp sysUserResp = sysThreadLocal.get();

        //优先从线程变量取，取到就返回
        if (sysUserResp != null) {
            return sysUserResp;
        }

        //从httpsession中获取
        HttpSession httpSession = getSession();
        if (httpSession != null) {
            sysUserResp = (BusUserResp) httpSession.getAttribute(WebConst.SESSION_USER);
            return sysUserResp;
        }

        return null;
    }

    public static final BusUserResp getSysUser() {

        BusUserResp sysUserResp = sysThreadLocal.get();
        log.info("userThreadLocal.get() resp={} ", JSON.toJSONString(sysUserResp));

        //优先从线程变量取，取到就返回
        if (sysUserResp != null) {
            return sysUserResp;
        }

        //从httpsession中获取
        HttpSession httpSession = getSession();
        if (httpSession != null) {
            sysUserResp = (BusUserResp) httpSession.getAttribute(WebConst.SESSION_USER);
            log.info("httpSession.getAttribute(WebConst.SESSION_USER) resp={} ", JSON.toJSONString(sysUserResp));
            return sysUserResp;
        }

        return null;
    }



    /**
     * 设置登录信息到session中.
     *
     * @param userDTO 登录信息
     * @author Ji.kai 2018-11-5
     */
//    public static final void setUser(SysUserDTO userDTO) {
//        HttpSession session = getSession();
//        if (session == null) {
//            return;
//        }
//        // 写入session
//        session.setAttribute(WebConst.SESSION_USER, userDTO);
//        // 设置线程变量
//        userThreadLocal.set(userDTO);
//        log.info("添加用户信息到session中，userDTO={}", userDTO);
//    }

    public static final void setSysUser(BusUserResp userDTO) {
        HttpSession session = getSession();
        if (session == null) {
            return;
        }
        // 写入session
        session.setAttribute(WebConst.SESSION_USER, userDTO);
        // 设置线程变量
        sysThreadLocal.set(userDTO);
        log.info("添加用户信息到session中，userDTO={}", userDTO);
    }



}

